import React from "react";

// 错误类型
export interface ApiError {
  code: number;
  message: string;
  details?: unknown;
}

// 错误处理函数
export const handleError = (error: Error | ApiError) => {
  // 对401错误进行特殊处理
  if ('code' in error && error.code === 401) {
    console.debug('Auth error (401):', error.message);

    // 清除认证信息并重定向到登录页
    localStorage.removeItem('auth-storage');
    localStorage.removeItem('userInfo');
    localStorage.removeItem('userPermissions');

    // 避免重复重定向
    if (window.location.pathname !== '/login' && !window.location.pathname.includes('/login')) {
      console.log('Redirecting to login due to 401 error');
      window.location.href = '/login';
    }
    return;
  }

  // 对网络错误进行静默处理
  if (error.message.includes('Network Error')) {
    console.debug('Network error:', error.message);
    return;
  }

  // 其他错误才打印完整日志
  console.error("Error:", error);
};

// 错误上报函数
export const reportError = (error: Error | ApiError, context?: any) => {
  console.error("Error reported:", error, context);
};

export class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    console.error("Error:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return React.createElement("div", null, "Something went wrong.");
    }
    return this.props.children;
  }
}
